import {ref} from "vue";
import api from "@/api/index.js";

const map = ref(new Map())
const queue = ref([])

function queueHas(url,id){
    let flag = false
    queue.value.forEach(item=>{
        if(item.url===url&&item.id===id)
            flag=true
    })
    return flag
}

// {url,id}
const queueQuery = setInterval(()=>{
    while(queue.value.length>0){
        let arg = queue.value.pop()
        if(queueHas(arg.url,arg.id))
            continue
        console.log('cacheMiss::'+arg.url+arg.id)
        api.get(arg.url+'/'+arg.id).then(resp=>{
            map.value.set(arg.url+arg.id,resp.data)
        })
    }
},300)
const get = (url,id)=>{
    if(!url||!id)
    {
        console.log('not valid')
        return
    }
    if(map.value.has(url+id)){
        console.log('cacheHit::'+url+id)
        return map.value.get(url+id)
    }else{
        if(!queueHas(url,id)) {
            console.log("push to queue")
            queue.value.push({url, id})
        }
        return null
    }
}

const flush = (url,id)=>{
    if(map.value.has(url+id)){
        map.value.delete(url+id)
    }
    api.get(url+'/'+id).then(resp=>{
        map.value.set(url+id,resp.data)
    })
}

const getData = (id)=>{
    if(map.value.has(id))
        return map.value.get(id)
}

const setData = (id,data)=>{
    map.value.set(id,data)
}

export default{
    get,getData,setData,flush
}